import { Component, OnInit } from '@angular/core';
import { MemberService } from '../../../services/organization/member/member.service';
import { RoleService } from '../../../services/organization/Role/role.service';
import { DepartmentService } from '../../../services/organization/department/department.service';
import { Utils, Lang, Status } from '../../../common/helper/util-helper';
import { NzFormatEmitEvent, NzTreeNode, NzFormatBeforeDropEvent, NzTreeComponent, NzModalService, NzMessageService } from 'ng-zorro-antd';
import { of, Observable, from } from 'rxjs';
import { TemplatePortalDirective } from '@angular/cdk/portal';
// import { Data } from '../../project/self-check/self-check-list/self-check-list.component';
import { Params } from '@angular/router';
@Component({
  selector: 'app-member',
  templateUrl: './member.component.html',
  styleUrls: ['./member.component.scss']
})
export class MemberComponent implements OnInit {


  public status = {
    // 获取当前用户
    user: JSON.parse(window.localStorage.getItem('APDInfo'))['userName'],
    // 列表数据集合
    dataList: [],
    // 权限集合
    authority: [],
    // 部门源数据
    originOrgOptions: null,
    // 部门数据集合
    orgOptions: [],
    // 部门选择的数据
    orgValue: null,
    // 角色数据集合
    roleOptions: [],
    // 角色选择的数据
    roleValue: null,
    // 批量删除按钮状态
    delBtnStatus: false,
    // 全选状态
    allChecked: false,
    // 半选状态
    indeterminate: false,
    // 选择框当前选中的数据集合
    checkedDatas: [],
    // 关键词搜索
    filter: '',
    // 当前选中节点
    activedNode: null,
    // 待编辑节点
    editNode: null,
    // 修改结构模态框状态
    ischangeSort: false,
    // 新增部门模态框状态
    ismodify: false,
    // 编辑部门模态框状态
    isedit: false,
    // 删除部门模态框
    isDelete: false,
    // 重置密码模态框
    isReset: false,
    // 结构修改成功状态
    isOkLoading: false,
    // 状态按钮
    isLoding: false,
    // 防止用户重复点击
    statusDisabled: false,
    // 模态框按钮提交状态
    isConfirmLoading: false,
    // 新增部门模态框状态
    isadd: false,
    // 表单数据绑定集合
    member: {
      name: null,
      userName: null,
      pwd: null,
      emailAddress: null,
      phoneNumber: null,
      id: null
    },
    // 分页相关数据集合对象
    pager: {
      // 当前页
      pageIndex: 1,
      // 总记录数
      totalCount: 1,
      // 每页显示记录数
      pageSize: 10,
      // 总页数
      totalPages: 1
    },
    // 当前页面所需要的权限
    pagePermissions: [
      'APJ.System.User'
    ],
    // 当前页面权限
    pageAuthorty: { User: null }
  };



  // 初始化数据
  init() {


    // 刷新数据重置全选、半选状态, 批量删除按钮状态,清空选中项
    this.status.allChecked = false;
    this.status.indeterminate = false;
    this.status.checkedDatas = [];
    if (this.status.checkedDatas.length === 0) {
      this.status.delBtnStatus = true;
    }
    const pramas = {
      // 每页记录数
      maxResultCount: this.status.pager.pageSize,
      // 当前页数
      SkipCount: this.status.pager.pageIndex - 1,
      // 关键词搜索
      filter: this.status.filter,
    };
    this.memberService.GetUsers(pramas).then((res) => {
      if (res.success) {
        this.status.dataList = res.result.items || [];
        this.status.pager.totalCount = res.result.totalCount;
        this.status.pager.totalPages = res.result.totalCount;
      } else {
        this.message.warning(res.error.message);
      }
      console.log(this.status.dataList);
      // 加载部门选项
      const p = { MaxResultCount: 1000 };
      // tslint:disable-next-line: no-shadowed-variable
      this.departmentService.GetOrganizationUnits(p).then((res) => {
        if (res.success) {
          const Temp = res.result.items;
          // 保存服务器原数据
          this.status.originOrgOptions = res.result.items;
          const tempOrg = [];
          Temp.forEach(element => {
            // console.log(element)
            tempOrg.push({ label: element.displayName, value: element.id });
          });

          this.status.orgOptions = tempOrg;
        } else {
          this.message.warning(res.error.message);
        }
        // console.log(this.status.orgOptions)
        // console.log(this.status.originOrgOptions)
      });
      // 加载角色选项
      // tslint:disable-next-line: no-shadowed-variable
      this.roleService.GetRoles({ maxResultCount: 1000 }).then((res) => {
        if (res.success) {
          const Temp = res.result.items;
          const tempOrg = [];
          Temp.forEach(element => {
            tempOrg.push({ label: element.displayName, name: element.name, value: element.id });
          });
          this.status.roleOptions = tempOrg;
        } else {
          this.message.warning(res.error.message);
        }
        // console.log(this.status.roleOptions)
      });

    });
    // 获取权限列表
    this.memberService.GetAllPermissions().then((res) => {
      // console.log(res)
      if (res.success) {
        this.status.authority = res.result.items;
      } else {
        this.message.warning(res.error.message);
      }
    });
  }






  // 选中相关************************************************************************************************************
  /**
     * 全部选中
     * @param status <any> 全选框的选中状态
     */
  public checkAll(status: any, callBack?: Function) {
    this.status.dataList.forEach((data: any) => {
      let eachStatus;
      if (callBack) {
        eachStatus = callBack(data);
      }
      if (eachStatus !== false) {
        data['checked'] = status;
      }
    });
    this.refreshCheckboxStatus();
  }

  /**
   * 刷新(所有复选框)状态
   */
  private refreshCheckboxStatus() {
    const dataList = this.status.dataList;
    const allChecked = dataList.filter((value: any) => !value['disabled']).every((value: any) => value['checked'] === true);
    const allUnChecked = dataList.filter((value: any) => !value['disabled']).every((value: any) => !value['checked']);
    this.status.allChecked = allChecked;
    this.status.indeterminate = (!allChecked) && (!allUnChecked);
    // 获取当前选中的数据
    const checkedDatas = [];
    dataList.forEach((data) => {
      if (data['checked']) {
        checkedDatas.push(data);
      }
    });
    this.status.checkedDatas = checkedDatas;
    // 改变批量操作按钮状态
    this.status.delBtnStatus = !dataList.some((value: any) => value['checked']);
  }
  /**
   * 获取当前选中项
   */
  public getCheckedData() {
    return this.status.checkedDatas;
  }
  // 选中相关结束********************************************************************************************************



  // 选择框改变事件
  selChange(value: { label: string; value: any; }): void {
    console.log(value);
  }
  // 绑定 输入框
  compareFn = (o1: any, o2: any) => (o1 && o2 ? o1.value === o2.value : o1 === o2);




  /***********************************
  *  // 获取选中部门的所有父级ID        *
  * @param currentid 当前选择部门的ID   *
  * @param arr 后台获取的所有部门数据   *
  * @param res 返回的 ID 数组         *
  ***********************************/
  public deepTraversal(currentid, arr, res) {
    if (arr != null) {
      arr.forEach(ele => {
        if (ele.id === currentid) {
          if (ele.parentId) {
            res.push(ele.parentId);
            this.deepTraversal(ele.parentId, arr, res);
          } else {
            return;
          }
        }
      });
    }
    return res;
  }


  // 新增人员
  addRole() {
    this.status.isadd = true;
    // console.log(this.status.orgValue)
  }
  addSave() {
    // 用户名正则
    const userreg = /^[a-zA-Z\d]+$/;
    // 手机正则 2019.4.26 新增166、198、199号段
    const phonereg = /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/;
    // 邮箱正则
    const myreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
    if (!this.status.member.userName) {
      this.message.warning('名称不能为空');
      return;
    } else if (!userreg.test(this.status.member.userName)) {
      this.message.warning('用户名格式仅支持字母或数字，不区分大小写');
      return;
    } else if (!this.status.member.name) {
      this.message.warning('姓名不能为空');
      return;
    } else if (!this.status.member.phoneNumber) {
      this.message.warning('手机不能为空');
      return;
    } else if (this.status.member.phoneNumber.length != 11) {
      this.message.warning('手机号格式错误');
      return;
    } else if (!this.status.member.emailAddress) {
      this.message.warning('邮箱不能为空');
      return;
    } else if (!myreg.test(this.status.member.emailAddress)) {
      this.message.warning('邮箱格式错误');
      return;
    } else if (!this.status.orgValue) {
      this.message.warning('部门不能为空');
      return;
    } else if (!this.status.roleValue) {
      this.message.warning('角色不能为空');
      return;
    } else {
      // 当前选中的部门ID
      const id = this.status.orgValue.value;
      // 保存需要上传的部门ID的集合
      const organizationUnits = [];
      organizationUnits.push(id);
      // 找到选中部门的位置，如果它有parentId就保存进organizationUnits数组
      this.deepTraversal(id, this.status.originOrgOptions, organizationUnits);
      // console.log(organizationUnits)

      const params = {
        'user': {
          //   "id": data.id,
          'name': this.status.member.name,
          'userName': this.status.member.userName,
          'surname': this.status.member.userName,
          'EmailAddress': this.status.member.emailAddress,
          'phoneNumber': this.status.member.phoneNumber,
          'password': this.status.member.pwd,
          'isActive': true,
          'shouldChangePasswordOnNextLogin': false,
          'isTwoFactorEnabled': false,
          'isLockoutEnabled': false
        },
        'assignedRoleNames': [this.status.roleValue.name],
        'sendActivationEmail': false,
        'setRandomPassword': false,
        'organizationUnits': organizationUnits


      };
      this.status.isOkLoading = true;
      this.memberService.CreateOrUpdateUser(params).then((res) => {
        // console.log(res);
        if (res.success) {
          this.status.isadd = false;
          this.message.success('添加成功');
          this.init();
        } else {
          this.status.isadd = false;
          this.message.warning(res.error.message);
        }
        // 关闭输入框并清空输入框值
        this.cancelAddOredit();

      });
    }
  }

  // 编辑人员
  protected editRole(node) {
    // console.log(node);
    this.status.isedit = true;
    this.status.editNode = node;
    this.status.member.name = node.name;
    this.status.member.userName = node.userName;
    this.status.member.phoneNumber = node.phoneNumber;
    this.status.member.emailAddress = node.emailAddress;
    this.status.member.id = node.id;
    this.status.roleValue = { label: node.roles[0].displayName, name: node.roles[0].name, value: node.roles[0].roleId };
    this.status.orgValue = { label: node.organizationUnitName, value: node.organizationUnitId };
  }

  // 确定修改人员
  editSave() {
    // 用户名正则
    const userreg = /^[a-zA-Z\d]+$/;
    // 手机正则 2019.4.26 新增166、198、199号段
    const phonereg = /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/;
    // 邮箱正则
    const myreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
    if (!this.status.member.userName) {
      this.message.warning('名称不能为空');
      return;
    } else if (!userreg.test(this.status.member.userName)) {
      this.message.warning('用户名格式仅支持字母或数字，不区分大小写');
      return;
    } else if (!this.status.member.name) {
      this.message.warning('姓名不能为空');
      return;
    } else if (!this.status.member.phoneNumber) {
      this.message.warning('手机不能为空');
      return;
    } else if (this.status.member.phoneNumber.length != 11) {
      this.message.warning('手机号格式错误');
      return;
    } else if (!this.status.member.emailAddress) {
      this.message.warning('邮箱不能为空');
      return;
    } else if (!myreg.test(this.status.member.emailAddress)) {
      this.message.warning('邮箱格式错误');
      return;
    } else if (!this.status.orgValue) {
      this.message.warning('部门不能为空');
      return;
    } else if (!this.status.roleValue) {
      this.message.warning('角色不能为空');
      return;
    } else {
      // 当前选中的部门ID
      const id = this.status.orgValue['value'];
      // 保存需要上传的部门ID的集合
      const organizationUnits = [];
      organizationUnits.push(id);
      // 找到选中部门的位置，如果它有parentId就保存进organizationUnits数组
      this.deepTraversal(id, this.status.originOrgOptions, organizationUnits);
      // console.log(organizationUnits)

      const params = {
        'user': {
          'id': this.status.member.id,
          'name': this.status.member.name,
          'userName': this.status.member.userName,
          'surname': this.status.member.userName,
          'EmailAddress': this.status.member.emailAddress,
          'phoneNumber': this.status.member.phoneNumber,
          'password': this.status.member.pwd,
          'isActive': this.status.editNode.isActive,
          'shouldChangePasswordOnNextLogin': false,
          'isTwoFactorEnabled': false,
          'isLockoutEnabled': false
        },
        'assignedRoleNames': [this.status.roleValue.name],
        'sendActivationEmail': false,
        'setRandomPassword': false,
        'organizationUnits': organizationUnits
      };
      // this.status.isOkLoading = true;
      // console.log(params);
      this.memberService.CreateOrUpdateUser(params).then((res) => {
        // console.log(res)
        if (res.success) {
          this.message.success('修改成功');
          this.init();
        } else {
          this.message.warning(res.error.message);
        }
        // 关闭输入框并清空输入框值
        this.cancelAddOredit();

      });
    }



  }
  // 取消编辑或添加
  cancelAddOredit() {

    this.status.editNode = null;
    this.status.isedit = false;
    this.status.isadd = false;
    this.status.isOkLoading = false;
    this.status.orgValue = null;
    this.status.roleValue = null;
    // tslint:disable-next-line: forin
    for (const i in this.status.member) {
      this.status.member[i] = null;
    }
    console.log('数据已清除');
  }

  // 修改人员状态
  clickSwitch(node) {
    this.status.statusDisabled = true;
    const params = {
      userId: node.id
    };
    this.memberService.UpdateActiveStatus(params).then((res) => {
      // console.log(res)
      if (res.success) {
        this.message.success('修改成功');
      } else {
        this.message.warning(res.error.message);
      }
      this.status.statusDisabled = false;
      // this.init()
    });
  }

  // 删除人员
  protected delRole(node) {
    // this.status.isDelete = true;
    this.status.editNode = node;
    this.status.member.name = node.name;
    this.mzModal.error({
      nzTitle: '删除组织',
      nzContent: '<p>删除后不能恢复，请谨慎操作。</p>',
      nzOnOk: () => this.delNode(),
      nzOkText: '确定',
      nzOkType: 'danger',
      nzCancelText: '取消',
      nzOnCancel: () => { }
    });
    // console.log(node)
    // this.status.title = this.status.editNode.displayName;
  }
  // 确定删除人员
  delNode() {
    const params = {
      id: this.status.editNode.id
    };
    // console.log(params)
    this.memberService.DeleteUser(params).then((res) => {
      if (res.success) {
        this.message.success('删除成功');
        this.init();
      } else {
        this.message.error(Utils.errorMessageProcessor(res, Lang.deleteFail));
      }
      this.status.isDelete = false;
      this.status.editNode = null;
      this.status.activedNode = null;
      this.cancelAddOredit();
    });
  }

  // 取消删除
  Canceldel() {
    this.status.isDelete = false;
    this.status.editNode = null;
    this.status.activedNode = null;

  }
  // 批量删除人员？
  public delmembers() {
    this.mzModal.error({
      nzTitle: '批量删除',
      nzContent: '<p>确认要批量删除吗？删除后无法恢复</p>',
      nzOnOk: () => this.delRoles(),
      nzOkText: '确定',
      nzOkType: 'danger',
      nzCancelText: '取消',
      nzOnCancel: () => { }
    });
  }
  // 批量删除人员
  delRoles() {
    const params = [];
    this.getCheckedData().forEach((item) => {
      params.push(item.id);
    });
    // console.log(params);
    if (params) {
      this.memberService.BatchDeleteUser(params).then((res) => {
        if (res.success) {
          this.message.success('删除成功');
        } else {
          this.message.warning(res.error.message);
        }

        // 重新加载
        this.init();
      });
    }
  }

  // 重置密码
  public resetPassword(data: any) {
    this.mzModal.confirm({
      nzTitle: '重置密码 ?',
      nzContent: '<p>确认要重置该账号的密码吗？重置后密码为当前账号</p>',
      nzOnOk: () => this.resetPasswordSure(data)
    });
  }
  /**
     *
     * 重置密码请求
     * @param data <any> 当前被重置密码用户信息
     */
  private resetPasswordSure(data: any) {
    this.memberService.ResetPasswordByAdmin({ userId: data.id }).then((res: any) => {
      if (res.success) {
        this.message.success('重置密码成功');
      } else {
        this.message.error(Utils.errorMessageProcessor(res));
      }
    });
  }


  /*分页相关******************************************************************************** */
  /**
  * 刷新列表
  */
  public refreshDataList() {
    const refresh = this['init'].bind(this);
    if (refresh) {
      refresh();
    }
  }

  /**
   * 列表分页
   * @param index <number> 非必填，列表跳转至第几页，默认为当前页(即刷新当前页数据)
   */
  public pageIndexChange(index?: any) {
    // console.log(index)
    const pager = this.status.pager;
    pager.pageIndex = index || pager.pageIndex;
    this.refreshDataList();
  }

  /**
   * 改变每页记录条数
   * @param size <number> 非必填
   */
  public pageSizeChange(size?: number) {
    const pager = this.status.pager;
    pager.pageSize = size || pager.pageSize;
    this.pageIndexChange();
  }

  /**********************************************************************************分页相关结束 */

  /**
   * 关键字搜索
   */
  public searchEvent() {
    // 搜索时重置分页
    this.status.pager.pageIndex = 1;
    this.init();
  }

  /**
   * 搜索框回车事件
   * @param e <Event>
   */
  public keyupEvent(e: Event) {
    Utils.enter(e, this.searchEvent.bind(this));
  }




  // tslint:disable-next-line: max-line-length
  constructor(public memberService: MemberService, public roleService: RoleService, public departmentService: DepartmentService, public message: NzMessageService, public mzModal: NzModalService) { }

  ngOnInit() {
    // 初始化批量删除按钮状态
    this.status.delBtnStatus = !this.status.dataList.some((value: any) => value['checked']);
    this.init();

  }

}
